package cn.iocoder.yudao.module.hs.dal.redis.no;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 订单序号的 Redis DAO
 */
@Repository
public class OrderNoRedisDAO {

    public static final String ENTRY_ORDER_NO_PREFIX = "WE";

    public static final String PICK_TASK_NO_PREFIX = "PT";

    public static final String RECEIVE_NO_PREFIX = "RO";

    public static final String SHIP_ORDER_NO_PREFIX = "SO";

    public static final String QC_ORDER_NO_PREFIX = "QC";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成序号
     *
     * @param prefix 前缀
     * @return 序号
     */
    public String generate(String prefix, String redisKeyPrefix) {
        // 递增序号
        String noPrefix = prefix + DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN);
        String key = redisKeyPrefix + noPrefix;
        Long no = stringRedisTemplate.opsForValue().increment(key);
        if (no != null && no == 10000) {
            no = 1L;
            stringRedisTemplate.opsForValue().set(key, String.valueOf(no));
        }
        // 设置过期时间
        stringRedisTemplate.expire(key, Duration.ofDays(1L));
        return noPrefix + String.format("%04d", no);
    }
}
